package com.web.server;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.sql.*;

@WebServlet(urlPatterns = "/download")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/demo";
            Connection conn = DriverManager.getConnection(url, "root", "root");
            PreparedStatement stmt = conn.prepareStatement("select password from users where username = ?");
            stmt.setString(1, userName);
            ResultSet rs = stmt.executeQuery();
            String result = "";
            if (rs.next()) {
                result = rs.getString("password");
            }

            if (password.equals(result)) {
                resp.getWriter().write("登录成功");
            } else {
                resp.getWriter().write("账号或密码错误");
            }
            stmt.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
